'use strict';

import React, { Component } from 'react';

import {
  StyleSheet,
  View,
  Text,
  TextInput,
  ListView,
} from 'react-native';

import {NavigationBar} from 'react-native-navigator'
import SQLite from '../react-native-sqlite';
import fs from 'react-native-fs';

class SQLiteComponent extends Component {
  constructor(props) {
    super(props);
  
    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: ()=> true}),
      dataList: []
    };

    this.sql = ''
  }

  componentDidMount() {
    this.db = new SQLite(`${fs.HOME}/sqlite.test.db`);
  }

  componentWillUnmount() {
    this.db.close();
  }

  render() {
    return (
      <View style={styles.container}>
        <NavigationBar navigator={this.props.navigator} title='SQLite'/>
        <View style={styles.header}>
          <TextInput 
            ref='input' 
            style={styles.input} 
            multiline autoFocus
            onChangeText={(text)=> this.sql = text}
          />
          <View style={{alignSelf: 'stretch', marginLeft: 7, justifyContent: 'space-around'}}>
          <Text onPress={()=>this.executeSQL()}>Clear</Text>
          <Text onPress={()=>this.executeSQL()}>Execute</Text>
          </View>
        </View>
        <ListView 
          ref='ListView'
          enableEmptySections
          dataSource={this.state.dataSource.cloneWithRows(this.state.dataList)}
          renderRow={(rowData)=> {
            return (
              <View style={{flexDirection: 'row'}}>
                {rowData.map((data, index)=><Text key={index} style={{flex: data.flex}}>{data.text}</Text>)}
              </View>
            );
          }}
        />
      </View>
    );
  }

  executeSQL() {
    this.db._execute(this.sql).then((result)=>{
      const flex = {};
      console.log(result);
      result.forEach((row)=> {
        row.forEach((column, index)=> {
          column = `${column}`;
          flex[index] = Math.max(column.length, flex[index] || 0);
        });
      });
      result = result.map((row)=>{
        return row.map((column, index)=> {return {text: `${column}`, flex: flex[index]};});
      });
      result.splice(1, 0, [{text: ' ', flex: 1}]);
      const dataList = [[{text: '>>>'+this.sql, flex: 1}], ... result, ... this.state.dataList];

      this.setState({
        ... this.state,
        dataList
      })

    }).catch((e)=> {
      console.log(e);
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
    paddingTop: 64
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 7
  },
  input: {
    flex: 1,
    backgroundColor: 'white',
    height: 68
  }
});


export default SQLiteComponent;